<template>
  <div class="list" style="background: rgb(189, 153, 220)">
    <div class="left">
      <van-sidebar v-model="activeKey">
        <van-sidebar-item
          :to="{ name: 'List', params: { id: item.id } }"
          :title="item.name"
          v-for="item in categories"
          :key="item.id"
        />
      </van-sidebar>
    </div>
    <div class="right">
      <van-list v-model="loading" :finished="finished" @load="loadData">
        <van-card
          @click-thumb="toDetail(item.id)"
          v-for="(item, index) in products"
          :tag="index < 5 ? index + 1 + '' : ''"
          :num="item.amount"
          :key="item.id"
          :price="item.price"
          :title="item.name"
          :thumb="item.coverImage | dalImg"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { loadCategoriesAPI } from '@/services/categories';
import { loadDataAPI } from '@/services/products';
export default {
  data() {
    return {
      loading: false,
      finished: false,
      page: 1, //当前页
      pages: 1, //总页数
      activeKey: 0,
      products: [],
      categories: [],
    };
  },
  async created() {
    // this.loadData();
    console.log(this.$route.params);
    // this.activeKey = this.$route.params.id;
    const res = await loadCategoriesAPI();
    this.categories = res.data;
    this.activeKey = this.categories.findIndex((item) => item.id * 1 === this.$route.params.id * 1);
  },
  //组件内的路由拦截
  //路由地址改变但是组件被复用的时候调用
  beforeRouteUpdate(to, from, next) {
    this.products = []; //重置商品信息
    this.finished = false; //重置是否加载完成
    this.page = 1; //充值页码
    next();
    this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;

      const resProducts = await loadDataAPI(this.page, this.$route.params.id);
      this.products.push(...resProducts.data);
      this.pages = resProducts.pages;
      this.page += 1;
      this.loading = false;
      if (this.page > this.pages) {
        this.finished = true; //以后就不会再执行load事件
      }
    },
    toDetail(id) {
      this.$router.push({
        name: 'Detail',
        query: {
          id,
        },
      });
    },
  },
};
</script>

<style scoped>
.list {
  display: flex;
}
.right {
  height: 100%;
  overflow: auto;
  flex: 1;
}
</style>
